package com.example.chapter10http;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String word = ((EditText) findViewById(R.id.et)).getText().toString();
                String urlString = "https://echo.apifox.com/" + word;
                Log.d("读取开始", "读取--"+urlString);
                new ReadSomething().execute(urlString);
            }
        });


    }



    class ReadSomething extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String strResults = "";
            HttpURLConnection conn = null;
            try {
                URL myUrl = new URL(params[0]);

                conn = (HttpURLConnection) myUrl.openConnection();  //创建URL连接
                conn.setConnectTimeout(10000);

                InputStream inputStream = conn.getInputStream();  //读数据,得到的是字节流
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");//包装为字符流
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                String strLine = "";

                while ((strLine = bufferedReader.readLine()) != null) {
                    strResults = strResults + strLine + "\n";
                    System.out.println("读取到  --" + strLine);
                }
                bufferedReader.close();
                inputStreamReader.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                conn.disconnect();
            }

            return strResults;
        }

        @Override
        protected void onPostExecute(String string) {
            TextView tvResult = findViewById(R.id.tv_result);
            if (!string.isEmpty()) {
                tvResult.setText(string);
            } else {
                tvResult.setText("没有读取到数据");
            }
        }
    }
}